package org.example.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleAbstractTypeResolver;
import com.fasterxml.jackson.databind.module.SimpleModule;
import lombok.SneakyThrows;
import org.aspectj.weaver.loadtime.Aj;
import org.example.entity.AjaxResult;
import org.example.entity.User;
import org.example.security.TokenFilter;
import org.example.security.UserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource(name = "UserDetailServiceImpl")
    private UserDetailServiceImpl userDetailsService;

    @Resource
    private TokenFilter tokenFilter;

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @SneakyThrows
    @Bean
    public AuthenticationManager authenticationManager(){
        return super.authenticationManager();
    }

//    /**
//     * 排除静态资源，无需权限认证
//     * @param web
//     * @throws Exception
//     */
//    @Override
//    public void configure(WebSecurity web) throws Exception {
//        super.configure(web);
//    }


    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //关闭csrf，因为是前后端分离，无需通过cookie传递session id
        http.csrf().disable();
        //授权配置
        http.authorizeRequests().antMatchers("/login","/logout").anonymous().anyRequest().authenticated();
        //在执行UsernamePasswordAuthenticationFilter过滤器之前，先执行tokenFilter
        http.addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class);
    }

//    @SneakyThrows
//    private void toJson(HttpServletResponse response, int code, String msg) {
//         AjaxResult err = AjaxResult.err(code, msg);
//         response.setContentType("application/json;charset=UTF-8");
//         response.getWriter().write(new ObjectMapper().writeValueAsString(err));
//        response.getWriter().close();
//    }

    @Bean
    public ObjectMapper getJacksonObjectMapper(Jackson2ObjectMapperBuilder builder){
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        SimpleModule simpleModule = new SimpleModule();
        SimpleAbstractTypeResolver simpleAbstractTypeResolver = new SimpleAbstractTypeResolver();
        //添加接口映射子类
        simpleAbstractTypeResolver.addMapping(GrantedAuthority.class, SimpleGrantedAuthority.class);
        simpleModule.setAbstractTypes(simpleAbstractTypeResolver);
        objectMapper.registerModule(simpleModule);
        return objectMapper;
    }
}
